from PIL import Image, ImageDraw, ImageFont
import os,shutil
import class_mysql

def expand_image_with_text(image_path, text, expand_height=180, font_size=150):
    """Expand the bottom of an image and add a bold text annotation."""
    image = Image.open(image_path)
    width, height = image.size
    new_height = height + expand_height  # Increase space for better text visibility

    # Create new image with extra space at the bottom
    expanded_image = Image.new("RGB", (width, new_height), (255, 255, 255))
    expanded_image.paste(image, (0, 0))

    # Draw text annotation
    draw = ImageDraw.Draw(expanded_image)

    # Try loading a font, fallback to default
    try:
        font = ImageFont.truetype("msyhbd.ttc", font_size)
    except:
        font = ImageFont.load_default()

    # Calculate text position
    bbox = draw.textbbox((0, 0), text, font=font)  # Get text bounding box
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    text_x = (width - text_width) // 2
    text_y = height + (expand_height - text_height) // 2

    draw.text((text_x, text_y), text, fill=(0, 0, 0), font=font)

    return expanded_image

def make_final_image_square(image, final_size=2000, padding=50):
    """Expands image to make it a perfect square and resizes it to final_size (2000x2000)."""
    width, height = image.size
    new_size = max(width, height) + 2 * padding  # Ensure padding around edges
    square_image = Image.new("RGB", (new_size, new_size), (255, 255, 255))
    
    # Center the original image in the square canvas
    x_offset = (new_size - width) // 2
    y_offset = (new_size - height) // 2
    square_image.paste(image, (x_offset, y_offset))

    # Resize to final output size (2000x2000)
    resized_image = square_image.resize((final_size, final_size), Image.LANCZOS)
    return resized_image

def combine_images_with_title(image1_path, image2_path, output_path):
    """Combines two images horizontally with a title at the top, ensuring a 2000x2000px square output."""
    # Expand both images with labels ("Front" & "Back" text size now fully visible)
    expanded_image1 = expand_image_with_text(image1_path, "正面", font_size=120)
    expanded_image2 = expand_image_with_text(image2_path, "背面", font_size=120)

    # Ensure both images have the same height
    height = max(expanded_image1.height, expanded_image2.height)
    expanded_image1 = expanded_image1.resize((expanded_image1.width, height))
    expanded_image2 = expanded_image2.resize((expanded_image2.width, height))

    # Add spacing between the two images
    separator_width = 50
    combined_width = expanded_image1.width + expanded_image2.width + separator_width
    title_space = 250  # Space for title to fit 200px text
    gap_between_title_and_images = 150  # Ensure 120px gap
    combined_height = height + title_space + gap_between_title_and_images  # Extra space for title + gap

    # Create final image
    result_image = Image.new("RGB", (combined_width, combined_height), (255, 255, 255))

    # Paste expanded images with spacing in between
    result_image.paste(expanded_image1, (0, title_space + gap_between_title_and_images))
    result_image.paste(expanded_image2, (expanded_image1.width + separator_width, title_space + gap_between_title_and_images))

    # Draw "RESULT" title at the top
    draw = ImageDraw.Draw(result_image)
    
    try:
        font = ImageFont.truetype("msyhbd.ttc", 160)  # "RESULT" text size 200px
    except:
        font = ImageFont.load_default()

    # Get text bounding box for "RESULT"
    text = os.path.basename(output_path)
    bbox = draw.textbbox((0, 0), text, font=font)  
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    text_x = (combined_width - text_width) // 2
    text_y = (title_space - text_height) // 2  # Center text in title space

    draw.text((text_x, text_y), text, fill=(0, 0, 0), font=font)

    # Ensure the final image is a perfect square and resized to 2000x2000 pixels
    final_square_image = make_final_image_square(result_image, final_size=2000)

    # Save final image
    final_square_image.save(output_path)
    print(f"✅ Final image saved as {output_path} (2000x2000 pixels)")


# combine_images_with_title("front.jpg", "back.jpg", "8DT80491-黑白灰12.jpg")

def convert_png_to_jpg(directory):
    if not os.path.exists(directory):
        print(f"路径不存在: {directory}")
        return

    # 遍历目录下所有的 JPG/PNG 文件
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)

        # 只处理 PNG 文件，且文件名不包含 'pic'
        if filename.lower().endswith('.png') and 'pic' not in filename.lower():
            jpg_filename = os.path.splitext(filename)[0] + ".jpg"
            jpg_path = os.path.join(directory, jpg_filename)

            try:
                # 打开 PNG 文件
                with Image.open(file_path) as img:
                    # 转换为 RGB 模式（去掉透明通道）
                    rgb_img = img.convert('RGB')

                    # 质量压缩，确保不超过 2MB
                    quality = 95  # 初始质量
                    while True:
                        rgb_img.save(jpg_path, "JPEG", quality=quality)
                        if os.path.getsize(jpg_path) <= 2 * 1024 * 1024 or quality <= 10:
                            break
                        quality -= 5  # 逐步降低质量以控制大小

                # 删除原 PNG 文件
                os.remove(file_path)
                print(f"转换完成: {file_path} -> {jpg_path} (质量: {quality})")

            except Exception as e:
                print(f"处理文件 {file_path} 时出错: {e}")

def get_pic_dicts(directory,category):
    if not os.path.exists(directory):
        print(f"路径不存在: {directory}")
        return
    data1={}
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if filename.lower().endswith(('.jpg', '.png')):
            m_p=filename.split('&')[0]
            if m_p in data1:
                data1[m_p].append(file_path)
            else:
                data1[m_p]=[file_path]
    db = class_mysql.MySQLQuery(host="43.161.240.94", user="hcecpod_com", password="Xcd9sMZ9DMBBkbMf", database="hcecpod_com")
    db.connect()
    for m_p,paths in data1.items():
        tags={'pic':0,'show_back':0,'show_front':0,'square':0,'show_main':0,'detail':0}
        for path in paths:
            for tag in tags:
                if tag in path:
                    tags[tag]+=1
        if tags['pic'] and tags['show_back'] and tags['show_front'] and tags['square'] and tags['show_main'] and tags['detail']==2:
            model_name=m_p.split('_')[0]
            temp_dict=db.fetch_one("select style_name from data_model where name='"+model_name+"'")
            style_name=temp_dict['style_name']
            if style_name==None:
                for path in paths:
                    path_folder=os.path.join(directory,'错误',m_p+'#款号不在')
                    if not os.path.exists(path_folder):
                        os.makedirs(path_folder)
                    path_new=os.path.join(path_folder,os.path.basename(path))
                    shutil.move(path,path_new)
            else:
                switch_dict={'TEMU男装':'A6','TEMU女装':'A8','TEMU大童':'A7','TEMU亚洲女装':'A4','TEMU小童':'A7'}
                temp_dict=db.fetch_one("select count(*) from data_kuaimai_operater_number where operater_number like '%"+switch_dict[category]+"%'")
                count=temp_dict['count(*)']+1
                operater_number=switch_dict[category]+str(count).zfill(5)
                skc=style_name.split("#")[0]+'+'+operater_number
                path_front=''
                path_back=''
                tag_pic=0
                pic_paths=[]
                db.insert_data("data_kuaimai_operater_number",{'operater_number':operater_number,'m_p':m_p})
                for path in paths:
                    path_folder=os.path.join(directory,'上架图包',skc,style_name.split('#')[1])
                    if not os.path.exists(path_folder):
                        os.makedirs(path_folder)
                    if 'show_main' in path:
                        path_new=os.path.join(path_folder,'2.jpg')
                        shutil.copy(path,path_new)
                    if 'show_front' in path:
                        path_new=os.path.join(path_folder,'3.jpg')
                        shutil.copy(path,path_new)
                        path_front=path
                    if 'show_back' in path:
                        path_new=os.path.join(path_folder,'4.jpg')
                        shutil.copy(path,path_new)
                        path_back=path
                    if 'detail' in path:
                        path_new=os.path.join(path_folder,'5.jpg')
                        if os.path.exists(path_new):
                            path_new=os.path.join(path_folder,'6.jpg')
                        shutil.copy(path,path_new)
                    if 'square' in path:
                        path_new=os.path.join(path_folder,'1.jpg')
                        shutil.copy(path,path_new)
                    if 'pic' in path:
                        tag_pic+=1
                        pic_paths.append(path)
                if tag_pic==1:
                    path_folder=os.path.join(directory,'快麦图包',style_name.split('#')[0])
                    if not os.path.exists(path_folder):
                        os.makedirs(path_folder)
                    pic_path_new=os.path.join(directory,'快麦图包',style_name.split('#')[0],operater_number+'.png')
                    shutil.copy(pic_paths[0],pic_path_new)
                    result_name='（图）'+style_name.split('#')[0]+'%'+style_name.split('#')[1]+'+'+operater_number+'.png'
                    result_path=os.path.join(directory,'快麦图包',style_name.split('#')[0],result_name)
                    try:
                        combine_images_with_title(path_front,path_back,result_path)
                    except Exception as e:
                        print(e)
                                                    
                        
                        
                
                
        else:
            for path in paths:
                path_folder=os.path.join(directory,'错误',m_p+'#文件缺失')
                if not os.path.exists(path_folder):
                    os.makedirs(path_folder)
                path_new=os.path.join(path_folder,os.path.basename(path))
                shutil.move(path,path_new)
 
# 示例调用
# convert_png_to_jpg("C:/Users/YourName/Pictures")

def main(directory,category):
    convert_png_to_jpg(directory)
    get_pic_dicts(directory,category)
    print(category)

if __name__ == "__main__":
    main("D:/Desk/temu批上款/男装", "TEMU男装")